<template>
  <Popup v-model:show="showModal" title="选择附近的店铺" @submit="onSubmit" @cancel="onCancel">
    <Item v-if="shopList.length > 0" v-for="itm in shopList" :key="itm.id" :shop="itm" :active="paramShopid === itm.id"
      @choose="onChoose"></Item>
    <view class="color-gray" v-else>暂无附近的门店</view>
  </Popup>
</template>

<script setup>
import { watch, ref, onMounted } from "vue"
import Popup from "@/components/ui/popup"
import Item from "./index.vue"
import { useShowModal } from "@/path/hooks/v-model"
import service from "@/path/service"
import { getUserLocation } from "@/path/location";
const props = defineProps({
  show: Boolean,
  title: String,
  name: String,
  shopid: String,
  type: String,
})
const emit = defineEmits(['update:show', 'update:shopid', 'update:name', "submit"])
const { showModal } = useShowModal(props, emit)

const shopList = ref([])

onMounted(() => {
  getUserLocation().then((res) => {
    return service.get("api/ycg/home/nearshop", {
      lat: res.latitude,
      lng: res.longitude,
      //1销售网点2售后网点，默认销售网点
      shopType: props.type || 1,
      distance: 2000
    })
  }).then((res) => {
    shopList.value = res
  })
})

const paramShopid = ref(props?.shopid || {})
watch(() => props.shopid, () => {
  paramShopid.value = props.shopid;
}, { immediate: true, deep: true });
function onChoose(shop) {
  paramShopid.value = shop.id
}
function onSubmit() {
  const _item = (shopList.value || []).find(v => v.id === paramShopid.value)
  if (!paramShopid.value || !_item) return
  emit("update:shopid", paramShopid.value);
  emit("update:name", _item.name);
  emit("submit", _item);
}
function onCancel() {
  emit("update:params", null);
  emit("update:name", "");
}
</script>

<style lang="less" scoped>
.color-gray {
  width: 100%;
  color: #666;
  text-align: center;
  height: 100rpx;
  line-height: 100rpx;
}
</style>
